package com.bolehui.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bolehui.base.enums.UserTypeEnum;
import com.bolehui.base.result.PageResult;
import com.bolehui.base.result.Result;
import com.bolehui.base.utils.DateUtil;
import com.bolehui.base.utils.StringUtils;
import com.bolehui.domain.dto.ConversationDTO;
import com.bolehui.domain.dto.JobDTO;
import com.bolehui.domain.dto.PassCountDTO;
import com.bolehui.domain.po.Conversation;
import com.bolehui.domain.po.Message;
import com.bolehui.mapper.ConversationMapper;
import com.bolehui.mapper.MessageMapper;
import com.bolehui.service.ConversationService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.YearMonth;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * @author chendongjie     email:chendongjie@gz.iscas.ac.cn
 * @version 1.0
 * @ClassName ConversationServiceImpl
 * @Description
 * @createTime 2025/3/15-13:47
 * Copyright (C) 2021-2022 CASEEDER, All Rights Reserved.
 * 注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的
 */
@Service
public class ConversationServiceImpl  extends ServiceImpl<ConversationMapper, Conversation> implements ConversationService {

    @Autowired
    private ConversationMapper conversationMapper;
    @Autowired
    private MessageMapper messageMapper;
    /**
     * 创建会话
     *
     * @param employerId 招聘者ID
     * @param candidateId 求职者ID
     * @return 创建的会话对象
     */
    public Result createConversation(Long employerId, Long candidateId, String jobName) {
        // 检查是否已存在相同的会话
        Conversation existingConversation = conversationMapper.selectOne(
                new QueryWrapper<Conversation>()
                        .eq("employer_id", employerId)
                        .eq("candidate_id", candidateId)
        );

        if (existingConversation != null) {
            // 如果会话已存在，直接返回
            return Result.success("已存在相同的会话");
        }

        // 创建新的会话
        Conversation conversation = new Conversation();
        conversation.setEmployerId(employerId);
        conversation.setCandidateId(candidateId);
        conversation.setCreateTime(DateUtil.getCurDate());
        conversation.setViewState("已投递");
        conversation.setProgress("初筛");
        // 插入会话到数据库
        conversationMapper.insert(conversation);

        // 发送初始消息
        Message initialMessage = new Message();
        initialMessage.setSenderId(candidateId); // 接收者为求职者
        initialMessage.setReceiverId(employerId); // 接收者为求职者发送者为招聘者
        initialMessage.setContent("你好,请问"+jobName+"还在招吗？我很感兴趣希望可以进一步沟通"); // 初始消息内容
        initialMessage.setConversationId(conversation.getId()); // 关联会话ID

        // 保存初始消息
        messageMapper.insert(initialMessage);

        // 返回创建的会话对象
        return Result.success();
    }

    @Override
    public Result listConversation(Long id, UserTypeEnum userType) {
        QueryWrapper<Conversation> queryWrapper = new QueryWrapper<>();

        // 根据用户类型设置查询条件
        if (userType == UserTypeEnum.Enterprise) {
            queryWrapper.eq("employer_id", id); // 查询招聘者的对话
        } else if (userType == UserTypeEnum.JobHunter) {
            queryWrapper.eq("candidate_id", id); // 查询求职者的对话
        } else {
            throw new IllegalArgumentException("无效的用户类型");
        }
        List<Conversation> conversations = conversationMapper.selectList(queryWrapper);
        int unread = 0;
        for (Conversation conversation : conversations) {
            Long conversationId = conversation.getId();
            List<Message> messages = messageMapper.selectList(new QueryWrapper<Message>().eq("conversation_id", conversationId).orderByAsc("create_time"));
            if(CollectionUtils.isEmpty(messages)){
                return Result.success(conversations);
            }
            for (Message message : messages) {
                if(message.getIsRead() == 0 && Objects.equals(message.getReceiverId(), id)){
                    unread++;
                }
            }
            Message message = messages.get(messages.size() - 1);
            conversation.setLastMessage(message.getContent());
            conversation.setUnread(unread);
        }

        // 查询对话列表
        return Result.success(conversations);
    }

    @Override
    public Result listByCompanyId(Long companyId, Integer pageNum, Integer pageSize ) {
        if(companyId == null){
            return Result.fail("ID不能为空");
        }
        if (ObjectUtil.isNull(pageNum)) {
            pageNum = 1;
        }
        if (ObjectUtil.isNull(pageSize)) {
            pageSize = 10;
        }
        // 开始分页
        PageHelper.startPage(pageNum, pageSize);
        // 查询数据库
        List<ConversationDTO> conversations = conversationMapper.listByCompanyIdWithPage(companyId);

        if(CollectionUtils.isEmpty(conversations)){
            return Result.success();
        }

        PageInfo<ConversationDTO> pageInfo = new PageInfo<>(conversations);
        // 创建 PageResult 对象
        PageResult<ConversationDTO> pageResult = new PageResult<>(pageInfo);
        return Result.success(pageResult);
    }

    @Override
    public Result doDeliveryProgress(Long id, String deliveryStatus) {
        if(id == null){
            return Result.fail("传入的id有误");
        }
        if(StringUtils.isEmpty(deliveryStatus)){
            return Result.fail("传入的投递情况有误");
        }
        if(deliveryStatus.equals("不合格")){
            Conversation conversation = new Conversation();
            conversation.setId(id);
            conversation.setViewState("不合格");
            conversationMapper.updateById(conversation);
            return Result.success("操作成功");
        }
        if(deliveryStatus.equals("初筛")){
            Conversation conversation = new Conversation();
            conversation.setId(id);
            conversation.setProgress("面试");
            conversationMapper.updateById(conversation);
            return Result.success("操作成功");
        }
        if(deliveryStatus.equals("面试")){
            Conversation conversation = new Conversation();
            conversation.setId(id);
            conversation.setProgress("录用");
            conversationMapper.updateById(conversation);
            return Result.success("操作成功");
        }
        if(deliveryStatus.equals("录用")){
            Conversation conversation = new Conversation();
            conversation.setId(id);
            conversation.setViewState("已录用");
            conversation.setProgress(" ");
            conversationMapper.updateById(conversation);
            return Result.success("操作成功");
        }
        return Result.fail("传入参数有误");
    }

    @Override
    public Result getResumeStatsLastSixMonths() {
        // 获取近六个月的起止日期
        YearMonth current = YearMonth.now();
        List<YearMonth> lastSixMonths = IntStream.rangeClosed(0, 5)
                .mapToObj(i -> current.minusMonths(5 - i)) // 从5个月前到当前月
                .collect(Collectors.toList());

        // 查询每个月的岗位数量
        List<Long> counts = lastSixMonths.stream()
                .map(month -> {
                    LocalDate startDate = month.atDay(1);
                    LocalDate endDate = month.atEndOfMonth();
                    return conversationMapper.countByCreateTimeBetween(startDate, endDate);
                })
                .collect(Collectors.toList());
        return Result.success(counts);
    }

    @Override
    public Result getPreviewStatsLastSixMonths() {
        PassCountDTO statistic = conversationMapper.getPreviewStatistics();
        return Result.success(statistic);
    }
}
